package com.secsbrain.development.dal.config;

import com.alibaba.fastjson.JSON;
import feign.Request;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;

import java.util.*;

/**
 * feign请求拦截器
 * 所有用feign发出的请求的拦截器，注意是feign作为客户端发出请求的，而不是服务端。
 * 这个在在项目代码中的任何位置都可以，需要在每个服务端验证这个全局参数。
 *
 * @author yjy
 */
public class FeignRequestInterceptor implements RequestInterceptor {

    private static final Logger log = LoggerFactory.getLogger(FeignRequestInterceptor.class);

    private Environment environment;

    @Autowired(required = false)

    public FeignRequestInterceptor(Environment environment) {
        this.environment = environment;
    }

    @Override
    public void apply(RequestTemplate requestTemplate) {
        String path = requestTemplate.path();
        if (path.contains("deployservice")) {
            Map<String, Collection<String>> paramMap = requestTemplate.queries();
            String env = paramMap.containsKey("env") ? ((List<String>) paramMap.get("env")).get(0) :
                    (paramMap.containsKey("envName") ? ((List<String>) paramMap.get("envName")).get(0) : "");
            if (StringUtils.isEmpty(env)) {
                Request.Body body = requestTemplate.requestBody();
                int length=body.length();
                if (length != 0 && StringUtils.isNotEmpty(body.asString())) {
                    Map<String, Object> map = JSON.parseObject(body.asString(), Map.class);
                    env = map.containsKey("env") ? map.get("env").toString() :
                            (map.containsKey("envName") ? map.get("envName").toString() : "");
                }
            }

            if (StringUtils.isNotEmpty(env)) {
                //这里可以添加feign请求的全局参数
                requestTemplate.header("loadBalancerKey", env);
            }

        }

        if (log.isDebugEnabled()) {
            log.debug("Rpc RequestHeaders > {}, Querys > {}", requestTemplate.headers(), requestTemplate.queries());
        }
    }
}